<template>
  <!-- 日常值班 -->
  <div class="wrapper">
    <div class="flex location-wrap">
      <span class="white">当前位置：</span>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/DutyIndex' }">值班管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/EmergencyDailyPlanList' }">应急值班</el-breadcrumb-item>
        <el-breadcrumb-item>值班</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-row style="height: 95%;margin-top: 10px;" :gutter="15">
      <el-col :span="7" style="height: 100%;">
        <DutyLeft ref="DutyLeft" @cutFrom="cutFrom" @getDate="getDate" :dutyCategory="dutyCategory" />
      </el-col>
      <el-col :span="17" style="height: 100%;">
        <div class="right-wrapper">
          <div class="title-but" v-show="titleBut">
            <el-button @click="oneClickSync">一键同步</el-button>
            <!-- <el-button>自动填充</el-button> -->
          </div>
          <!-- 应急 -->
          <RightEmergencyForm v-if="dutyCategory == 'RightEmergencyForm'" :ref="dutyCategory"
            :titleConfig="titleConfig" />
          <!-- 预警 -->
          <RightWarningForm v-else :ref="dutyCategory" :titleConfig="titleConfig" />
          <div class="footer-btn">
            <!-- operator_leader  值班长 operator_staff 值班员 operator_director 值班主任 shift_leader 带班领导 -->
            <div v-if="submitBut && getParseStamp(calendarDate) == getParseStamp(new Date())">
              <el-button type="primary" @click="onSubmit({ reportApprovalStatus: 1 })">提交</el-button>
              <el-button @click="onSubmit({ reportApprovalStatus: 0 })">保存</el-button>
            </div>
            <div v-if="approveBut">
              <el-button type="primary" @click="onApprover({ reportApprovalStatus: 3 })">审批</el-button>
              <el-button @click="onApprover({ reportApprovalStatus: 2 })">驳回</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import DutyLeft from "./dutyLeft/idnex.vue";
import RightWarningForm from "./dutyRinght/rightWarningForm.vue";
import RightEmergencyForm from "./dutyRinght/rightEmergencyForm.vue";
import { getDetail, submitLogOrDailyApi, oneClickSync } from "@/api/duty/daily/plan.js";
import { parseStamp } from "@/utils/public.js";
import { warningTitleConfig, emergencyTitleConfig } from "./dutyRinght/config";
import { flowSubmit } from "@/utils/flow";
export default {
  name: "DailyDaily",
  components: {
    DutyLeft,
    RightWarningForm,
    RightEmergencyForm
  },
  data() {
    return {
      leftTabsKey: "值班计划",
      calendarDate: new Date(),
      warningTitleConfig,
      emergencyTitleConfig,
      titleConfig: emergencyTitleConfig,
      dutyCategory: "RightEmergencyForm", // 1应急 2预警
      titleBut: false,
      approveBut: false,
      submitBut: false
    };
  },
  computed: {
    roleCode() {
      return JSON.parse(sessionStorage.getItem("role"))?.roleCode;
    }
  },
  methods: {
    getParseStamp(date = new Date(), format = "YYYY-MM-DD") {
      return parseStamp(date, format);
    },
    cutFrom(activeName) {
      this.leftTabsKey = activeName;
    },
    getDate(e, obj = {}) {
      this.calendarDate = e;
      this.getDetail(obj);
    },
    // 提交  保存
    onSubmit(data) {
      this.$refs[this.dutyCategory].submitValidate().then(async res => {
        if (res) {
          const dutyDate = parseStamp(this.calendarDate, "YYYY-MM-DD");
          const params = Object.assign(res, { dutyDate, type: "2", dutyType: "2" }, data);
          if (data.reportApprovalStatus == 1) {
            if (!res.id) {
              const id = await submitLogOrDailyApi(params);
              params.id = id;
            }
            const submitData = {
              bizKey: params.id,
              flowKey: this.dutyCategory == "RightEmergencyForm" ? "duty_emergency_004" : "duty_emergency_003",
              taskId: "task1",
              callbackUrl: "/duty/dutyReport/handleFlow",
              idea: "1",
              variable: params
            };
            const successCallBack = () => {
              this.$message({
                message: `提交成功`,
                type: "success"
              });
              this.getDetail();
              this.$refs.DutyLeft.getTableData();
            };
            await flowSubmit(submitData, successCallBack, "提交", true);
          } else {
            const id = await submitLogOrDailyApi(params);
            if (id) {
              this.$message({ message: `保存成功`, type: "success" });
              this.getDetail();
              this.$refs.DutyLeft.getTableData();
            }
          }
        }
      });
    },
    // 工作流审批
    gzlAudit(type, variable) {
      const data = {
        bizKey: variable.id,
        flowKey: this.dutyCategory == "RightEmergencyForm" ? "duty_emergency_004" : "duty_emergency_003",
        taskId: "task2",
        callbackUrl: "/duty/dutyReport/handleFlow",
        idea: type == 2 ? "0" : "1",
        variable,
        ideaMsg: variable.approvalOpinion
      };
      const successCallBack = () => {
        this.$message({
          message: `${type === 3 ? "审核" : "驳回"}成功`,
          type: "success"
        });
        this.getDetail();
        this.$refs.DutyLeft.getTableData();
      };
      flowSubmit(data, successCallBack, "审核");
    },
    // 审批 // 驳回
    onApprover(data) {
      this.$refs[this.dutyCategory].submitValidate().then(async res => {
        if (res) {
          const dutyDate = parseStamp(this.calendarDate, "YYYY-MM-DD");
          const params = Object.assign({
            id: res.id,
            dutyDate,
            type: "2",
            dutyType: "2",
            approvalOpinion: res.approvalOpinion || (data.reportApprovalStatus == 3 ? "同意" : "驳回"),
            approvalUser: this.$refs[this.dutyCategory].formData.approvalUser,
            approvalUserId: this.$refs[this.dutyCategory].formData.approvalUserId,
            approvalDept: this.$refs[this.dutyCategory].formData.approvalDept,
            approvalTime: this.$refs[this.dutyCategory].formData.approvalTime
          }, data);
          this.gzlAudit(data.reportApprovalStatus, params);
        }
      });
    },

    async getDetail(data) {
      try {
        const time = parseStamp(this.calendarDate, "YYYY-MM-DD");
        const account = JSON.parse(sessionStorage.getItem("account"));
        // const user = JSON.parse(sessionStorage.getItem("org"));
        this.$refs[this.dutyCategory].isEdit = false;
        this.approveBut = false;
        this.submitBut = false;
        this.titleBut = false;
        const res = await getDetail(Object.assign({ userId: account.id, reportDate: time, dutyType: "2", type: 2 }, data));
        if (res) {
          this.dutyCategory = res.dutyCategory == 2 ? "RightWarningForm" : "RightEmergencyForm";
          // 值班审批状态0：编辑中  1：待审批  2：驳回   3：已审批
          // const reportApprovalStatus = res.reportApprovalStatus;
          this.titleConfig = JSON.parse(JSON.stringify(res.dutyCategory == 2 ? warningTitleConfig : emergencyTitleConfig));
          this.initialization(res);
          if (!res.canFillOut) return;
          if (res.canFillOut.indexOf("operator_staff") != -1) { // 值班员
            this.$refs[this.dutyCategory].formData.creator = res.creator || account.realName;
            this.$refs[this.dutyCategory].formData.dutyPersonId = res.creatorId || account.id;
            this.$refs[this.dutyCategory].formData.createDeptName = res.createDeptName || sessionStorage.dwbmName;
            this.$refs[this.dutyCategory].formData.reportTime = res.createTime || parseStamp(new Date());
            this.approveBut = false;
            this.$refs[this.dutyCategory].isApprover = false;
            this.operator_staff(res);
          } else if (res.canFillOut.indexOf("operator_leader") != -1) { // 值班长  值班主任
            this.titleBut = false;
            this.$refs[this.dutyCategory].isEdit = false;
            this.submitBut = false;
            this.operator_leader(res, account);
          } else if (res.canFillOut.indexOf("shift_leader") != -1) { // 带班领导
            this.$refs[this.dutyCategory].isApprover = false;
            this.titleBut = false;
            this.$refs[this.dutyCategory].isEdit = false;
            this.submitBut = false;
            this.approveBut = false;
          }

        } else {
          this.$refs[this.dutyCategory].resetData();
          this.$refs[this.dutyCategory].isEdit = false;
        }
      } catch (err) {
        this.$refs[this.dutyCategory].formData.reportName = "";
        this.$refs[this.dutyCategory].resetData();
        this.$refs[this.dutyCategory].isEdit = false;
      }
    },
    initialization(res) {
      if (res.reportApprovalStatus != null) {
        const arr = Object.keys(this.$refs[this.dutyCategory].formData);
        arr.forEach(item => { this.$refs[this.dutyCategory].formData[item] = res[item]; });
        this.$refs[this.dutyCategory].formData.id = res.id;
        this.$refs[this.dutyCategory].formData.dutyAttendanceId = res.dutyAttendanceId;
        if (res.approvalUserId) {
          this.titleConfig.push({
            title: "审批信息",
            name: "5",
            slot: "slot5"
          });
        }
      } else {
        this.$refs[this.dutyCategory].resetData();
        this.$refs[this.dutyCategory].formData.reportName = res.reportName;
        this.$refs[this.dutyCategory].formData.dutySource = res.dutySource;
      }
    },
    operator_staff(res) {
      if (this.leftTabsKey == "值班日报") {
        if (res.reportApprovalStatus == 1 || res.reportApprovalStatus == 3) {
          this.titleBut = false;
          this.$refs[this.dutyCategory].isEdit = false;
          this.submitBut = false;
        } else {
          this.titleBut = this.getParseStamp(this.calendarDate) == this.getParseStamp(new Date());
          this.$refs[this.dutyCategory].isEdit = this.getParseStamp(this.calendarDate) == this.getParseStamp(new Date());
          this.submitBut = true;
        }
      } else {
        this.titleBut = false;
        this.$refs[this.dutyCategory].isEdit = false;
        this.submitBut = false;
      }
    },
    operator_leader(res, account) {
      if (this.leftTabsKey == "值班日报") {
        if (res.reportApprovalStatus == 1 && res.isApproved == 1) {
          this.titleConfig.push({
            title: "审批信息",
            name: "5",
            slot: "slot5"
          });
          this.$refs[this.dutyCategory].formData.approvalUser = account.realName;
          this.$refs[this.dutyCategory].formData.approvalUserId = account.id;
          this.$refs[this.dutyCategory].formData.approvalDept = sessionStorage.dwbmName;
          this.$refs[this.dutyCategory].formData.approvalTime = parseStamp(new Date());
          this.$refs[this.dutyCategory].isApprover = true;
          this.approveBut = true;
        } else {
          this.$refs[this.dutyCategory].isApprover = false;
          this.approveBut = false;
        }
      } else {
        this.$refs[this.dutyCategory].isApprover = false;
        this.approveBut = false;
      }
    },
    async oneClickSync() {
      const time = parseStamp(this.calendarDate, "YYYY-MM-DD");
      const account = JSON.parse(sessionStorage.getItem("account"));
      const res = await oneClickSync({ userId: account.id, reportDate: time, dutyType: "2", type: 2 });
      if (res) {
        const arr = Object.keys(this.$refs[this.dutyCategory].formData);
        arr.forEach(item => {
          if (res[item]) this.$refs[this.dutyCategory].formData[item] = res[item];
        });
        this.$refs[this.dutyCategory].formData.approvalUser = "";
        this.$refs[this.dutyCategory].formData.approvalDept = "";
        this.$refs[this.dutyCategory].formData.approvalTime = "";
      }
    }

  }
};
</script>

<style lang='less' scoped>
.wrapper {
  height: 100%;

  :deep(.el-breadcrumb) {
    font-size: 16px;
  }

  .location-wrap {
    line-height: 25px;
  }
}

.right-wrapper {
  padding: 20px 40px;
  background-color: #fff;
  border-radius: 4px;
  height: 100%;
  overflow-y: auto;
  font-size: 16px;
  box-sizing: border-box;

  .title-but {
    display: flex;
    justify-content: flex-end;
  }

  .submit-btn {
    display: flex;
    align-content: center;
    justify-content: center;
  }
}

.footer-btn {
  >div {
    display: flex;
    align-content: center;
    justify-content: center;
  }
}
</style>
